package com.qk.management.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtil;
import com.qk.domain.user.UserDO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: Enid
 * @date: 2025/10/7 18:15
 * @description: 用户管理实现类
 */
@Service
public class UserServiceImpl implements UserService {

    private static final String DEFAULT_PASSWORD_SUFFIX = "123";
    private static final Integer USER_STATUS_UNNORMAL = 0;
    @Autowired
   private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 用户登录
     * @return userLoginVO
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        boolean hasNullField = BeanUtil.hasNullField(userLoginDTO);
        if (hasNullField){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        User dbUser = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (Objects.isNull(dbUser)){
            CommonException.throwCommonException(ParamEnum.LOGIN_USERNAME_ERROR);
        }
        if (ObjectUtil.equals(USER_STATUS_UNNORMAL,dbUser.getStatus())){
            CommonException.throwCommonException(ParamEnum.USER_STATUS_ERROR);
        }
        String userPassword = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        String enCodedPassword = dbUser.getPassword();

        boolean isCheck = ObjectUtil.equals(userPassword, enCodedPassword);
        if (!isCheck){
            CommonException.throwCommonException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }

        Role role = roleMapper.selectById(dbUser.getRoleId());
        String roleLabel = role.getLabel();


        Map<String,Object> claims = new HashMap<>();
        claims.put("id",dbUser.getId());
        claims.put("username",dbUser.getUsername());

        return UserLoginVO.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(roleLabel)
                .token(JwtUtil.generateToken(claims))
                .build();
    }

    @Override
    public void update(User user) {
        boolean hasNull = BeanUtil.hasNullField(user,"id","password","roleId","deptId","image","remark","updateTime","createTime");
        if(hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);

    }

    @Override
    public User selectById(Integer id) {
        if (Objects.isNull(id))
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        return userMapper.selectById(id);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        userMapper.deleteByIds(ids);
    }

    @Override
    public List<User> listOfRole(String roleLabel) {
        Role role = roleMapper.selectByLabel(roleLabel);
        if (ObjectUtils.isEmpty(role))
            throw new RuntimeException("角色不存在");
        return userMapper.listOfRole(role.getId());
    }

    @Override
    public List<User> listOfDept(Integer deptId) {
        if (Objects.isNull(deptId))
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        return userMapper.listOfDept(deptId);

    }
    @Override
    public void addUser(User user) {

        boolean hasNull = BeanUtil.hasNullField(user,"id","password","roleId","deptId","image","remark","updateTime","createTime");
        if(hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }

        String rawPassword = new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD_SUFFIX).toString();

        String enCodedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(enCodedPassword);

        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
    }

    @Override
    public PageResult<UserDO> list(UserDTO userDTO) {

        PageHelper.startPage(userDTO.getPage(),userDTO.getPageSize());
        List<UserDO> result =userMapper.list(userDTO);
        Page<UserDO> page = (Page<UserDO>) result;
        return PageResult.<UserDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public List<User> all() {
        return userMapper.all();
    }
}
